package com.webserver.core;

import com.webserver.annotations.Controller;
import com.webserver.annotations.RequestMapping;

import java.io.File;
import java.lang.reflect.Method;
import java.net.URISyntaxException;
import java.sql.Connection;
import java.util.HashMap;
import java.util.Map;

public class HandlerMapping {
    private static Map<String, Method> mapping = new HashMap<>();

    static {
        initMapping();
    }

    public static void initMapping() {
        try {
            File rootDir = new File(
                    HandlerMapping.class.getClassLoader().getResource(".").toURI()
            );
            File dir = new File(rootDir, "com/webserver/controller");
            File[] files = dir.listFiles(f -> f.getName().endsWith(".class"));
            for (File file : files) {
                String classname = file.getName().replaceAll(".class", "");
                Class cls = Class.forName("com.webserver.controller." + classname);
                if (cls.isAnnotationPresent(Controller.class)) {
                    Method[] method = cls.getDeclaredMethods();
                    for (Method method1 : method) {
                        if (method1.isAnnotationPresent(RequestMapping.class)) {
                            RequestMapping rm = method1.getAnnotation(RequestMapping.class);
                            String value = rm.value();
                            mapping.put(value, method1);
                        }
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static Method getMethod(String uri){
        return mapping.get(uri);
    }
}
